package hsintiao.com.xintiaoAPP.service.impl;

import hsintiao.com.xintiaoAPP.entity.Comment;
import hsintiao.com.xintiaoAPP.entity.Reply;
import hsintiao.com.xintiaoAPP.entity.User;
import hsintiao.com.xintiaoAPP.mapper.ArticleDetailsMapper;
import hsintiao.com.xintiaoAPP.mapper.UserMapper;
import hsintiao.com.xintiaoAPP.service.ArticleDetailsService;
import hsintiao.com.xintiaoAPP.util.AjaxResult;
import hsintiao.com.xintiaoAPP.util.ResponseCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ArticleDetailsServiceImpl implements ArticleDetailsService {
    @Autowired
    private ArticleDetailsMapper articleDetailsMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public AjaxResult getComment(Long articleId) {
        try {
            List<Comment> comments = articleDetailsMapper.getComments(articleId);
            return AjaxResult.me().setResultObj(comments);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setCode(ResponseCode.FAILURE.getCode())
                    .setSuccess(false).setMessage("查询失败");
        }
    }

    @Override
    @Transactional
    public AjaxResult leaveMessage(Comment comment) {
        try {
            User user = userMapper.getUserByID(comment.getUserId());
            comment.setUsername(user.getName());
            comment.setAvatar(user.getAvatar());
            articleDetailsMapper.insertComment(comment);
            return AjaxResult.me();
        }catch (Exception e){
            return AjaxResult.me().setCode(ResponseCode.FAILURE.getCode())
                    .setSuccess(false).setMessage("评论失败");
        }
    }

    @Override
    @Transactional
    public AjaxResult leaveReply(Reply reply) {
        try {
            User me = userMapper.getUserByID(reply.getMeId());
            User send = userMapper.getUserByID(reply.getSendId());
            reply.setMeName(me.getName());
            reply.setSendName(send.getName());
            articleDetailsMapper.isnertRepy(reply);
            return AjaxResult.me().setResultObj(reply);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setCode(ResponseCode.FAILURE.getCode())
                    .setSuccess(false).setMessage("回复失败");
        }
    }
}
